package com.czy.owner.ui.order;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.czy.owner.R;
import com.czy.owner.alipay.PayResult;
import com.czy.owner.db.UserHelper;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.setting.ForgetPaidPasswordActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.wxapi.WXPayEntryActivity;
import com.input.password.ui.InputPwdView;
import com.input.password.ui.MyInputPwdUtil;
import com.input.password.ui.PaidErrorDialog;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wangayng on 2017/6/12 0011.
 * 订单付款
 */
public class OrderPaidActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_payment)
    TextView tvPayment;
    @BindView(R.id.rel_store_bannce)
    RelativeLayout relStoreBannce;
    @BindView(R.id.view_store_bannce)
    View viewStoreBannce;
    @BindView(R.id.tv_use_yue)
    TextView tvUseYue;//可用余额
    @BindView(R.id.cb_yue)
    CheckBox cbYue;//使用余额CheckBox
    @BindView(R.id.cb_zhifubao)
    CheckBox cbZhiFuBao;//支付宝CheckBox
    @BindView(R.id.cb_weixin)
    CheckBox cbWeiXin;//微信CheckBox
    @BindView(R.id.tv_sdk_paid_tip)
    TextView tvSdkPaidTip;
    private static final int SDK_PAY_FLAG = 1;//支付
    private String seletPaidType = "aliPay";
    //    private String useStoreBalance = "false";
    private double realityPaid = 0.00; //实际支付
    private double storeBalance = 0.00;
    private MyInputPwdUtil myInputPwdUtil;

    private int storeId;
    private double totalPrice;
    private String orderNumber;
    private String name;
    private String contact;
    private String address;
    private String orderType;
    //        private int fromGoodsId;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paidSuccessInfo();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PhoneUtils.ShowToastMessage(OrderPaidActivity.this, "支付失败");
                    }
                    break;
                }


            }
        }

    };


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_order_paid;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.package_paid);
        RxBus.getDefault().register(this);
        storeId = getIntent().getIntExtra("storeId", 0);
        totalPrice = getIntent().getDoubleExtra("totalPrice", 0.00);
        orderNumber = getIntent().getStringExtra("orderNumber");
        name = getIntent().getStringExtra("name");
        contact = getIntent().getStringExtra("contact");
        address = getIntent().getStringExtra("address");
        orderType = getIntent().getStringExtra("orderType");
        SharedPreferencesUtils.setParam(OrderPaidActivity.this, Constants.SHARED_PREFERENCES_KEY_RECEIVER_TOTALPRICE, String.format("%.2f", totalPrice) + "");
        SharedPreferencesUtils.setParam(OrderPaidActivity.this, Constants.SHARED_PREFERENCES_KEY_RECEIVER_NAME, name);
        SharedPreferencesUtils.setParam(OrderPaidActivity.this, Constants.SHARED_PREFERENCES_KEY_RECEIVER_CONTACT, contact);
        SharedPreferencesUtils.setParam(OrderPaidActivity.this, Constants.SHARED_PREFERENCES_KEY_RECEIVER_ADDRESS, address);
        tvPayment.setText("付款金额(元): " + String.format("%.2f", totalPrice));
        MyLog.e("yang", "orderType==" + orderType);
        if (storeId != 0 && !orderType.contains("system") && !orderType.contains("transfer")) {
            viewStoreBannce.setVisibility(View.VISIBLE);
            relStoreBannce.setVisibility(View.VISIBLE);
            userStoreBalance();
        } else {
            viewStoreBannce.setVisibility(View.GONE);
            relStoreBannce.setVisibility(View.GONE);
        }

        myInputPwdUtil = new MyInputPwdUtil(this);
        myInputPwdUtil.getMyInputDialogBuilder().setAnimStyle(R.style.ActionSheetDialogAnimation);
        myInputPwdUtil.setListener(new InputPwdView.InputPwdListener() {
            @Override
            public void hide() {
                myInputPwdUtil.hide();
            }

            @Override
            public void forgetPwd() {
                startActivity(new Intent(OrderPaidActivity.this, ForgetPaidPasswordActivity.class));
            }

            @Override
            public void finishPwd(String pwd) {
                bannceVerifyPayPassword(pwd);
            }
        });
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentStart();
            }
        });
    }

    @Override
    protected void updateViews() {

    }


    //余额支付
    @OnClick(R.id.cb_yue)
    public void cbYuEOnClick(View view) {
        if (cbYue.isChecked()) {
            if (realityPaid >= 0) {  //当门店余额大于等于实际支付余额时
                cbZhiFuBao.setChecked(false);
                cbWeiXin.setChecked(false);
                tvSdkPaidTip.setVisibility(View.GONE);
                seletPaidType = "11";
            }
        } else {
            cbYue.setChecked(true);
        }

    }

    //支付宝支付
    @OnClick(R.id.cb_zhifubao)
    public void cbZhiFuBaoOnClick(View view) {
        if (cbZhiFuBao.isChecked()) {
            cbWeiXin.setChecked(false);
            cbYue.setChecked(false);
            seletPaidType = "aliPay";
        } else {
            cbZhiFuBao.setChecked(true);
        }

    }

    //微信支付
    @OnClick(R.id.cb_weixin)
    public void cbWeiXinOnClick(View view) {
        if (cbWeiXin.isChecked()) {
            cbZhiFuBao.setChecked(false);
            cbYue.setChecked(false);
            seletPaidType = "wxPay";
        } else {
            cbWeiXin.setChecked(true);
        }


    }

    //    支付宝调用
    private void aliPayPaid(final String data) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(OrderPaidActivity.this);
                // 调用支付接口，获取支付结果
                Map<String, String> result = alipay.payV2(data, true);
                MyLog.e("yang", "result==" + result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //确认支付
    @OnClick(R.id.btn_sure_paid)
    public void btnSureOnClick(View view) {
        if (cbYue.isChecked()) {
            myInputPwdUtil.show();
        } else {
            payAmount();

        }
    }

    private void bannceVerifyPayPassword(String payPassword) {
        String url = Constants.APP_API_BASE + Constants.OWN_VERIFYPAYPASSWORD;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(OrderPaidActivity.this).getSession());
        params.addBodyParameter("payPassword", payPassword);
        params.addBodyParameter("userId", UserHelper.getInstance().getUserInfoModel(OrderPaidActivity.this).getUserId() + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);

                String exp = JsonUtil.getJsonValuesString(result, "exp");
                boolean flag = JsonUtil.getJsonValuesBoolean(result, "flag");
                int count = JsonUtil.getJsonValuesInt(result, "data");

                if (flag) {
                    myInputPwdUtil.hide();
                    payAmount();
                } else {
                    switch (count) {
                        case 1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(OrderPaidActivity.this, myInputPwdUtil);
                            break;
                        case 2:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paidPswErrorDialog(OrderPaidActivity.this, myInputPwdUtil);
                            break;
                        case 3:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(OrderPaidActivity.this, exp);
                            break;
                        case -1:
                            myInputPwdUtil.hide();
                            PaidErrorDialog.paid30AfterDialog(OrderPaidActivity.this, exp);
                            break;
                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void userStoreBalance() {
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_PRE_QUICK_PAYMENT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String data = PhoneUtils.checkResponseFlag(OrderPaidActivity.this, result);
                if (data != null) {
                    storeBalance = JsonUtil.getJsonValuesDouble(data, "storeBalance");
                    tvUseYue.setText("¥" + String.format("%.2f", storeBalance));
                    realityPaid = storeBalance - totalPrice;
                    if (storeBalance == 0 || realityPaid < 0) {
                        cbYue.setClickable(false);
                    } else {
                        cbYue.setClickable(true);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }


            @Override
            public void onFinished() {

            }
        });
    }

    private void payAmount() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDERS_PAYMENT;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
        if (cbYue.isChecked()) {
            params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(OrderPaidActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        }
        params.addBodyParameter("orderNumber", orderNumber);
        if (seletPaidType.equals("aliPay") || seletPaidType.equals("wxPay")) {
            params.addBodyParameter("payType", seletPaidType);
        }
        params.addBodyParameter("useStoreBalance", cbYue.isChecked() + "");
        MyLog.e("yang", "params==" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "支付定金onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(OrderPaidActivity.this, result);
                if (data.equals("")) {
                    paidSuccessInfo();
                } else {
                    if (seletPaidType.equals("aliPay")) {
                        aliPayPaid(data);
                    } else if (seletPaidType.equals("wxPay")) {
                        if (isWXAppInstalledAndSupported()) {
                            WXPayEntryActivity.wxPayPaidStart(OrderPaidActivity.this, data, "订单付款成功");
                        } else {
                            PhoneUtils.ShowToastMessage(OrderPaidActivity.this, getString(R.string.isInstallwx));
                        }
                    }
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }

    //判断是否安装微信客户端
    public boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(WXPayEntryActivity.APP_ID);
        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled() && msgApi.isWXAppSupportAPI();
        return sIsWXAppInstalledAndSupported;
    }

    private void paidSuccessInfo() {
        Intent ti = new Intent(OrderPaidActivity.this, BackPaidSuccessActivity.class);
        startActivity(ti);
        finish();
    }

    @Subscribe(code = Constants.ORDER_PAYMENT_SECCESS_CODE, threadMode = ThreadMode.MAIN)
    public void onPaymentSuccess(CommonEvent event) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(OrderPaidActivity.this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            intentStart();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void intentStart() {
       if (Constants.IS_START_ORDER_ACTIVITY)  {
            finish();
        }else {
           Intent intent2 = new Intent(OrderPaidActivity.this, OrderActivity.class);
           intent2.putExtra("currentId", 1);
           startActivity(intent2);
           finish();
       }
    }
}
